#include "server_locate.h"
#include <cstring>
#include <cstdlib>

using namespace std;
namespace PFS
{
    ServerLocate::ServerLocate()
    {
        alive = true;
        memset(&ds_info, 0, sizeof(DataServerInfo));
        elect_seq = 1;
        block_list.clear();
        writeable_blocks.clear();
        primary_blocks.clear();
    }

    ServerLocate::~ServerLocate()
    {
        this->clear();
    }

    DataServerInfo* ServerLocate::get_data_server()
    {
        return &ds_info;
    }

    const DataServerInfo* ServerLocate::get_data_server() const
    {
        return &ds_info;
    }

    const ServerLocate::BLOCK_SET* ServerLocate::get_block_list() const
    {
        return &block_list;
    }

    const ServerLocate::BLOCK_SET* ServerLocate::get_writable_blocks() const
    {
        return &writeable_blocks;
    }

    const ServerLocate::BLOCK_SET* ServerLocate::get_primary_writable_blocks() const
    {
        return &primary_blocks;
    }

    void ServerLocate::add_block(const uint32_t block_id)
    {
        block_list.insert(block_id);
    }

    void ServerLocate::add_writable_block(const uint32_t block_id)
    {
        writeable_blocks.insert(block_id);
    }

    void ServerLocate::add_primary_writable_block(const uint32_t block_id)
    {
        primary_blocks.insert(block_id);
    }

    void ServerLocate::remove_block(const uint32_t block_id)
    {
        block_list.erase(block_id);
    }

    void ServerLocate::remove_writable_block(const uint32_t block_id)
    {
        writeable_blocks.erase(block_id);
    }

    void ServerLocate::remove_primary_writable_block(const uint32_t block_id)
    {
        primary_blocks.erase(block_id);
    }

    void ServerLocate::release(const uint32_t block_id)
    {
        remove_block(block_id);
        remove_writable_block(block_id);
        remove_primary_writable_block(block_id);
    }

    void ServerLocate::clear()
    {
        block_list.clear();
        writeable_blocks.clear();
        primary_blocks.clear();
    }

    uint32_t ServerLocate::get_max_block_id() const
    {
        if(writeable_blocks.rbegin() != writeable_blocks.rend())
            return (*writeable_blocks.rbegin());
        return 0;
    }
}
